using B.Z.BasicData.Infrastructure;
using B.Z.Inventory.API.Read.Application.Command;
using B.Z.Inventory.API.Read.DTO;
using B.Z.Inventory.Domain;
using B.Z.Inventory.ErrorCode;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.Z.Inventory.API.Read.Application.CommandHandler
{
    /// <summary>
    /// 货品查询命令处理器
    /// </summary>
    public class GoodsQueryCommandHandler : IRequestHandler<GoodsQueryCommand, APIResult<APIPaging<GoodsDto>>>
    {
        private readonly IBaseRepository<T_Goods> goodsRepository;
        private readonly ILogger<GoodsQueryCommandHandler> logger;
        private readonly IBaseRepository<T_InventoryGoods> inventorygoodsRepository;

        public GoodsQueryCommandHandler(IBaseRepository<T_Goods> goodsRepository, ILogger<GoodsQueryCommandHandler> logger, IBaseRepository<T_InventoryGoods> inventorygoodsRepository)
        {
            this.goodsRepository = goodsRepository;
            this.logger = logger;
            this.inventorygoodsRepository = inventorygoodsRepository;
        }

        public Task<APIResult<APIPaging<GoodsDto>>> Handle(GoodsQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<GoodsDto>> result = new APIResult<APIPaging<GoodsDto>>();
            result.Code = APIEnums.ok;

            try
            {
                //根据主键获取到中间表的货品Ids
                var list = inventorygoodsRepository.GetAll().Where(x => x.InventoryId == request.Id).Select(x=>x.GoodsId);




                // 获取所有未删除的货品数据
                var query = goodsRepository.GetAll()
                    .AsNoTracking()
                    .Where(x => !x.IsDelete);

                // 应用搜索条件
                if (!string.IsNullOrEmpty(request.SearchKeyword))
                {
                    // 模糊查询货品名称、编号、规格
                    var keyword = request.SearchKeyword.Trim();
                    query = query.Where(x => 
                        x.GoodsName.Contains(keyword) || 
                        x.GoodsNumber.Contains(keyword) || 
                        x.GoodsModel.Contains(keyword));
                }


                // 应用具体字段筛选条件
                if (list.Count() > 0)
                {
                    query = query.Where(x => list.Contains(x.Id));
                }
                if (!string.IsNullOrEmpty(request.GoodsName))
                {
                    query = query.Where(x => x.GoodsName.Contains(request.GoodsName));
                }

                if (!string.IsNullOrEmpty(request.GoodsNumber))
                {
                    query = query.Where(x => x.GoodsNumber.Contains(request.GoodsNumber));
                }

                if (!string.IsNullOrEmpty(request.GoodsModel))
                {
                    query = query.Where(x => x.GoodsModel.Contains(request.GoodsModel));
                }

                // 转换为DTO
                var goodsQuery = query.Select(goods => new GoodsDto
                {
                    Id = goods.Id,
                    GoodsName = goods.GoodsName,
                    GoodsNumber = goods.GoodsNumber,
                    GoodsModel = goods.GoodsModel,
                    GoodsUnit = goods.GoodsUnit.ToString(), // 转换为字符串
                    SystemNum = goods.SystemNum,
                    ActualNum = goods.ActualNum,
                    DifferentCount = goods.DifferentCount,
                    CreateUserId = goods.CreateUserId,
                    CreateTime = goods.CreateTime,
                    UpdateUserId = goods.UpdateUserId,
                    UpdateTime = goods.UpdateTime,
                    IsDelete = goods.IsDelete,
                    OnePrice = goods.OnePrice
                });

                // 创建分页对象
                APIPaging<GoodsDto> paging = new APIPaging<GoodsDto>();
                paging.Count = goodsQuery.Count();
                paging.List = goodsQuery
                    .OrderByDescending(x => x.Id)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToList();

                result.Data = paging;
                
                logger.LogInformation($"成功获取货品列表，共{paging.Count}条记录，搜索关键词：{request.SearchKeyword}");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取货品列表时发生错误");
                result.Code = APIEnums.fail;
                result.Message = "获取货品列表失败";
            }

            return Task.FromResult(result);
        }
    }
}